package com.puyuba.puyuba.view.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.hjq.toast.ToastUtils;
import com.netease.nis.quicklogin.QuickLogin;
import com.netease.nis.quicklogin.listener.QuickLoginPreMobileListener;
import com.netease.nis.quicklogin.listener.QuickLoginTokenListener;
import com.puyuba.puyuba.MainActivity;
import com.puyuba.puyuba.R;
import com.pyb.java.commonutil.activity.ActivityManager;
import com.pyb.java.basemodule.BaseActivity;
import com.pyb.java.cache.CacheUserInfo;
import com.pyb.java.cache.SPHelper;
import com.pyb.java.cache.bean.UserInfoBean;
import com.pyb.java.commonutil.constant.RouterActivityPath;
import com.pyb.java.commonutil.utils.DeviceUtils;
import com.pyb.java.network.NetBaseApi;
import com.pyb.java.network.RequestBodyUtil;
import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.RetrofitManger;
import com.pyb.java.network.observers.ResponseObserve;

import com.pyb.java.network.scheduler.RxSchedulers;
import com.pyb.java.commonutil.ToastHelper;

import com.puyuba.puyuba.view.fragment.ServiceAgreementDialogFragment;
import com.pyb.module.ogin.LoginApi;
import com.pyb.module.ogin.utils.EaseIMUtils;
import com.puyuba.puyuba.utils.QuickLoginUiConfig;

import java.util.HashMap;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import io.reactivex.disposables.Disposable;
import okhttp3.RequestBody;

public class OneClickLoginActivity extends BaseActivity {

    private QuickLogin quickLogin;
    private ServiceAgreementDialogFragment serviceAgreementDialogFragment;
    private LinearLayout llParent;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.finishOther(this);
        llParent = findViewById(R.id.llParent);
        initService();

    }

    public void initData(){
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 0);
        if (SPHelper.getBoolean("isLogin", false)) {
            //3秒进入mainactivity
            llParent.postDelayed(() -> {
                ARouter.getInstance().build(RouterActivityPath.Main.PAGER_MAIN).navigation();
                finish();
            }, 2000);
        }else {
            initonelogin();
        }
    }
    /**
     * 初始化用户协议和隐私协议
     */
    private void initService() {
        SpannableString spannableString = new SpannableString(getString(R.string.login_service));
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                MainWebActivity.startMainWebActivity(OneClickLoginActivity.this, NetBaseApi.REGISETPROTOCOLURL,"用户注册协议");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);//去掉下划线
            }
        };
        if ("zh-CN".equals(DeviceUtils.getSystemLanguage())||"zh-TW".equals(DeviceUtils.getSystemLanguage())) {
            spannableString.setSpan(clickableSpan, 9, 16, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(OneClickLoginActivity.this, R.color.color_3ca8d9));
            spannableString.setSpan(colorSpan, 9, 16, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        } else {
            spannableString.setSpan(clickableSpan, 27, 42, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            ForegroundColorSpan colorSpan = new ForegroundColorSpan(ContextCompat.getColor(OneClickLoginActivity.this, R.color.color_3ca8d9));
            spannableString.setSpan(colorSpan, 27, 42, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }

        ClickableSpan clickableSpan2 = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                MainWebActivity.startMainWebActivity(OneClickLoginActivity.this,NetBaseApi.PRIVACYPOLICY,"隐私政策");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);//去掉下划线
            }

        };
        if ("zh-CN".equals(DeviceUtils.getSystemLanguage())||"zh-TW".equals(DeviceUtils.getSystemLanguage())) {
            spannableString.setSpan(clickableSpan2, 18, 23, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            ForegroundColorSpan colorSpan2 = new ForegroundColorSpan(ContextCompat.getColor(OneClickLoginActivity.this, R.color.color_3ca8d9));
            spannableString.setSpan(colorSpan2, 18, 23, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        } else {
            spannableString.setSpan(clickableSpan2, 46, 61, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            ForegroundColorSpan colorSpan2 = new ForegroundColorSpan(ContextCompat.getColor(OneClickLoginActivity.this, R.color.color_3ca8d9));
            spannableString.setSpan(colorSpan2, 46, 61, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }

        if (!SPHelper.getBoolean("agree")) {
            if (serviceAgreementDialogFragment == null) {
                serviceAgreementDialogFragment = new ServiceAgreementDialogFragment();
            }
            serviceAgreementDialogFragment.show(getFragmentManager(), "serviceAgreementDialogFragment");
        }else {
            initData();
        }
    }
    private void initonelogin() {
        quickLogin = QuickLogin.getInstance(this, "6759716b40194c0c9e2908a004af246a");
        quickLogin.prefetchMobileNumber(new QuickLoginPreMobileListener() {
            @Override
            public void onGetMobileNumberSuccess(String YDToken, String mobileNumber) {
                //预取号成功
                quickLogin.onePass(new QuickLoginTokenListener() {
                    @Override
                    public void onGetTokenSuccess(String YDToken, String accessCode) {
                        //一键登录成功 运营商token：accessCode获取成功
                        //拿着获取到的运营商token二次校验（建议放在自己的服务端）
                        if (QuickLoginUiConfig.getIsAgree()){
                            onelogin(YDToken,accessCode);
                            QuickLoginUiConfig.setIsAgree(false);
                        }else {
                            ToastUtils.show("请勾选协议");
                        }
                    }

                    @Override
                    public void onGetTokenError(String YDToken, String msg) {
                        quickLogin.quitActivity();
                        LoginActivity.startActivity(OneClickLoginActivity.this);
                    }
                });
            }

            @Override
            public void onGetMobileNumberError(String YDToken, String msg) {
                LoginActivity.startActivity(OneClickLoginActivity.this);
            }
        });
        quickLogin.setUnifyUiConfig(QuickLoginUiConfig.getUiConfig(OneClickLoginActivity.this));
    }

    private void onelogin(String YDToken, String accessCode){
        showLoadingDialog();
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", YDToken);
        map.put("accessToken", accessCode);
        RequestBody bodyByMap = RequestBodyUtil.getRequestBodyByMap(map);

        RetrofitManger.getInstance().createService(LoginApi.class)
                .onelogin(bodyByMap)
                .compose(RxSchedulers.<ResponseEntity<UserInfoBean>>applySchedulers())
                .subscribe(new ResponseObserve<UserInfoBean>(){

                    @Override
                    public void onSuccess(ResponseEntity<UserInfoBean> responseEntity) {
                        closeLoadingDialog();
                        UserInfoBean data = responseEntity.getData();
                        //存储用户信息
                        CacheUserInfo.getInstance().saveUserInfo(data);
                        EaseIMUtils.getInstance().signin(data.getUser().getHx_uid(),"123456");
                        quickLogin.quitActivity();
                        Intent intent = new Intent(OneClickLoginActivity.this, MainActivity.class);
                        //这个标记，将会导致任何用来放置该activity的已经存在的task里面的已经存在的activity先清空，然后该activity再在该task中启动，
                        // 也就是说，**这个新启动的activity变为了这个空task的根activity.所有老的activity都结束掉。该标志必须和FLAG_ACTIVITY_NEW_TASK一起使用。**

                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|intent.FLAG_ACTIVITY_NEW_TASK);
//                        intent.putExtra("userbean",data);
                        startActivity(intent);
                        finish();

                        ToastHelper.show( "登录成功");
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        closeLoadingDialog();
                        ToastHelper.show("一键登录失败");
                        LoginActivity.startActivity(OneClickLoginActivity.this);
                    }

                    @Override
                    public void onSubscribeStart(@io.reactivex.annotations.NonNull Disposable d) {
                        addDisposable(d);
                    }
                });
    }

    @Override
    public void onBackPressed() {
        finish();
    }
}
